import axios from 'axios'
// import {reject} from "eslint-plugin-promise/rules/lib/promise-statics";
import ElementUI from "element-ui";

axios.defaults.timeout = 5000 // 超时时间设置
axios.defaults.withCredentials = true // true允许跨域
// Content-Type 响应头
axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded;charset=UTF-8'
axios.defaults.baseURL="http://localhost:8888";

axios.interceptors.request.use(config => {
  let user = localStorage.getItem("sConsumer")?JSON.parse(localStorage.getItem("sConsumer")):null
  if (user) {
    config.headers['token'] = user.token;  // 设置请求头
  }
  return config
}, error => {
  return Promise.reject(error)
});

// 响应拦截器
axios.interceptors.response.use(
  response => {

    // 如果返回的状态码为200，说明接口请求成功，可以正常拿到数据
    // 否则的话抛出错误
    if (response.status === 200) {
      return Promise.resolve(response)
    } else {
      return Promise.reject(response)
    }
    //当权限验证不通过的时候给出提示
    let res = response.data
    if (res.code===1000){
      ElementUI.Message({
        message:res.message,
        type:'error'
      });
    }
    return res;
  },
  // 服务器状态码不是2开头的的情况
  error => {
    if (error.response.status) {
      switch (error.response.status) {
        // 401: 未登录
        case 401:;
          router.replace({
            path: "/",
            query: {
               redirect: router.currentRoute.fullPath
            },
          });
          break;
        case 404://没找到
          break;
      }
      return Promise.reject(error.response);
    }
  }
);


/**
 * 封装get方法
 * @param url
 * @param data
 * @returns {Promise}
 */
export function get(url, params={}) {
  return new Promise((resolve, reject) => {
    axios.get(url, {params:params}).then(
      response => {
        resolve(response.data);
      }
    )
      .catch(err=>{
        reject(err);
      })
  });
}

/**
 * 封装post请求
 * @param url
 * @param data
 * @returns {Promise}
 */
export function post(url,data={},config){
  return new Promise((resolve, reject) => {
    axios.post(url,data,config)
      .then(response=>{
        resolve(response.data);
      })
      .catch (err => {
        reject(err);
      })
  });
}


